package com.atguigu.flink.chapter05.Transform;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/8/9 10:30
 */
public class Flink11_Process {
    public static void main(String[] args) throws Exception {
        // 0.执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        // 1.读取数据
        //  sensor_1,123123213,10
        DataStreamSource<String> socketDS = env.socketTextStream("localhost", 9999);

        SingleOutputStreamOperator<WaterSensor> sensorDS = socketDS.map((MapFunction<String, WaterSensor>) value -> {
            String[] datas = value.split(",");
            return new WaterSensor(
                    datas[0],
                    Long.parseLong(datas[1]),
                    Integer.parseInt(datas[2])
            );
        });
//        sensorDS.process(new ProcessFunction<WaterSensor, String>() {
//            @Override
//            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
//                ctx.
//            }
//        })

        KeyedStream<WaterSensor, String> sensorKS = sensorDS.keyBy(r -> r.getId());

        // TODO
        SingleOutputStreamOperator<String> resultDS = sensorKS.process(new KeyedProcessFunction<String, WaterSensor, String>() {
            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                String currentKey = ctx.getCurrentKey();
                Long timestamp = ctx.timestamp();
                out.collect(currentKey + " <======> " + timestamp);
            }
        });

        resultDS.print();

        env.execute();
    }
}
/*
    process: 底层的算子
        1、分8大类：  在什么地方调用，就 继承 什么样的 ProcessFunction
        2、提供了一个上下文对象： 定时器、侧输出流、获取事件时间、 特定ProcessFunction的相关功能
        3、当你找不到现成的算子实现你的需求，考虑一下 process
 */